package cn.ivicar.app.guice;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletContextEvent;

import org.apache.log4j.xml.DOMConfigurator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.inject.Guice;
import com.google.inject.Injector;
import com.sun.jersey.api.core.PackagesResourceConfig;
import com.sun.jersey.guice.spi.container.servlet.GuiceContainer;

import cn.com.carsmart.sae.guice.SaeAopModule;
import cn.com.carsmart.util.configmanagement.ConfigUtil;
import cn.com.carsmart.util.configmanagement.FileSystemConfigReaderImpl;
import cn.com.carsmart.ws.guice.BasicGuiceServletModule;
import cn.com.carsmart.ws.guice.GuiceConfig;
import cn.com.carsmart.ws.guice.MybatisDataBaseModule;
import cn.com.carsmart.ws.model.IvicarObjectSet;
import cn.ivicar.app.controller.event.CloudEventHander;
import cn.ivicar.redis.pubsub.RedisPubSubFactory;

public class AppGuiceConfig extends GuiceConfig {

	private static transient final Logger LOGGER = LoggerFactory.getLogger(AppGuiceConfig.class);

	private static Injector injector = null;

	public AppGuiceConfig() {

	}

	public AppGuiceConfig(String environment) {
		this.environment = environment;
	}

//	@Override
//	public Injector getInjector() {
//
//		if (injector == null) {
//			String environment = this.getEnvironment();
//			injector = getInjector(environment);
//		}
//
//		return injector;
//	}

	public static Injector getStaticInjector() {
		return injector;
	}

	@Override
	public void contextInitialized(ServletContextEvent servletContextEvent) {
		super.contextInitialized(servletContextEvent);

		RedisPubSubFactory.subscribe("ivicar_event", new CloudEventHander());

		try {
			String logconfig = ((FileSystemConfigReaderImpl) ConfigUtil.getConfigReader()).getBasePath() + "/log4j.xml";
			LOGGER.info("加载日志配置文件[{}]", logconfig);
			DOMConfigurator.configure(logconfig);
		} catch (Exception e) {
			LOGGER.warn("加载日志配置文件出错， 使用本地配置");
		}
	}

//	public static Injector getInjector(final String environment) {
//		Injector injector = Guice.createInjector(
//				//TODO:待注入SampleModule
//				new MybatisDataBaseModule("ivicar", IvicarObjectSet.getSet()),
//				new SaeAopModule(environment, new String[] { "cn.ivicar.app" }),
//				new BasicGuiceServletModule() {
//					@Override
//					protected void configureServlets() {
//						this.setEnvironment(environment);
//						super.configureServlets();
//
//						Map<String, String> params = new HashMap<String, String>();
//						params.put(PackagesResourceConfig.PROPERTY_PACKAGES, "cn.ivicar.app");
//						serve("/ws/v1/*").with(GuiceContainer.class, params);
//					}
//				});

//		return injector;
//	}
}